package com.behome.netty.netty_D.bean;

import com.behome.netty.netty_D.enums.TerminalDAnnotation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class BusinessCmdBase {
    protected int sessionId = 0;

    public BusinessCmdBase() {
    }

    public abstract boolean validateBeforeSerialize();

    public abstract byte[] serialize();

    public abstract BusinessCmdBase deserialize(byte[] var1);

    public Packet generateSendPacket(int sessionId, String sourceCode, String[] targetCodes, boolean isSign) {
        return this.generateSendPacket(sessionId, PacketHead.PacketType.REQUEST, sourceCode, targetCodes, isSign);
    }

    public Packet generateSendPacket(int sessionId, PacketHead.PacketType packetType, String sourceCode, String[] targetCodes, boolean isSign) {
        try {
            this.sessionId = sessionId;
            Packet packet = new Packet();
            PacketBody body = new PacketBody(sourceCode, targetCodes, this);
            packet.setBody(body);
            short packetLength = (short) (12 + body.serialize().length + PacketTail.getLength(isSign));
            PacketHead head = new PacketHead(sessionId, packetType, isSign, packetLength);
            packet.setHead(head);
            PacketTail tail = new PacketTail(isSign, packet);
            packet.setTail(tail);
            return packet;
        } catch (Exception e) {
            log.error("程序异常" + e.toString());
        }
        return null;
    }

    public String getCmdInfo() {
        String ret = "未知";
        TerminalDAnnotation annotation = this.getClass().getAnnotation(TerminalDAnnotation.class);
        if (annotation != null) {
            ret = annotation.type().toString();
        }

        return ret;
    }

    public byte getCmdTypeValue() {
        TerminalDAnnotation annotation = this.getClass().getAnnotation(TerminalDAnnotation.class);
        return annotation != null ? annotation.type().getValue() : 0;
    }

    public String getSendCmdInfo() {
        String ret = "(会话标识:{sessionId},指令信息:{cmdInfo})";
        ret = ret.replace("{sessionId}", this.sessionId + "").replace("{cmdInfo}", this.getCmdInfo());
        return ret;
    }
}
